//封装请求
"use strict";
import axios from 'axios'
import store from "@/store";
import { removeToken,removeRefreshToken,getToken,getRefreshToken } from "@/utils/auth";

axios.defaults.timeout = 3000;
axios.defaults.headers.post[ 'Content-Type' ] = 'application/json;charset=UTF-8';


//wx.showLoading 和 wx.showToast 同时只能显示一个
let needLoadingRequestCount = 0
axios.defaults.adapter = function (config) {
  return new Promise((resolve, reject) => {
    let header = {}
    header['difference'] = 'prePaid'
    //如果token不为空
    if(getToken()){
      header['Authorization'] = `Bearer ${getToken()}`
      header['refreshToken'] = getRefreshToken()
    }
    wx.request({
      url:`${store.getters.baseurl}${config.url}`,
      method:config.method,
      data:config.params,
      header:header,
      success:(res)=>{
      return resolve(res)
    },
      fail:(err)=>{
        wx.showToast({
            title: "网络超时~", 
            icon: "none",
            duration:3000,
        });
        wx.reLaunch({
          url: `/pages/fail/main`,
      });
        
		return reject(err)
	  }
    })
  })
}

function Instance () {
  //请求拦截器
  axios.interceptors.request.use(function ( request ) {
    // console.log('请求',request)
    // wx.showLoading({
    //   title: '加载中...',
    // });
    needLoadingRequestCount++
    return request
  }, function ( error ) {
    console.log('request报错',error);
    return Promise.reject(error);
  });

  // 添加响应拦截器
  axios.interceptors.response.use(function ( response ) {
    // console.log('响应',response);
    let {statusCode} = response;
    console.log("拦截")
    console.log(statusCode)
    let navigateToRes = true;
    //判断后端接口的状态码。
    if(statusCode == 401){
      removeToken()
      removeRefreshToken()
      if(needLoadingRequestCount > 1){
        needLoadingRequestCount = 0
        wx.hideLoading()
        wx.login({
          success:(retunData)=>{
            let code = retunData.code
            store.dispatch("userLogin", code).then(item=>{
              console.log(item)
                if(item.statusCode == '00000'){
                  wx.reLaunch({
                    url: '/pages/home/main',
                  })
                }
            })
          }
        })
      }
      return Promise.resolve(res || 'error')
    }
    needLoadingRequestCount--
    return response.data;
  }, 
  function ( error ) {
    console.log('response报错',error);
    return Promise.reject(error);
  });
}

Instance()

function httpGet(config) {
  return axios({
    method:'get',
    url:config.url,
    params:config.params
  })
}
function httpPost(config) {
  return axios({
    method:'post',
    url:config.url,
    params:config.data
  })
}
export {
  httpGet,
  httpPost
}
